<template>
  <div class="fish-module">
    <!-- 搜索控件区域 -->
    <div class="filter-controls">
      <el-input 
        placeholder="搜索鱼类名称..." 
        v-model="fishSearch" 
        class="search-input"
        clearable
      >
        <template #append>
          <el-button icon="Search" @click="searchFishes">搜索</el-button>
        </template>
      </el-input>
    </div>
    
    <!-- 加载状态显示 -->
    <div v-if="loading" class="loading">
      <el-skeleton :rows="5" animated />
    </div>
    
    <!-- 错误状态显示 -->
    <div v-else-if="error" class="error">
      <el-alert
        :title="error"
        type="error"
        show-icon
      />
    </div>
    
    <!-- 搜索结果为空时显示 -->
    <div v-else-if="filteredFishes.length === 0 && fishSearch" class="no-data">
      <el-empty description="未找到相关鱼类" />
    </div>
    
      <!-- 鱼类列表显示部分 -->
  <el-row :gutter="20" class="fish-list" v-else>
  <el-col 
    :xs="24" 
    :sm="12" 
    :md="8" 
    v-for="fish in filteredFishes" 
    :key="fish.id"
  >
    <el-card class="fish-card" shadow="hover">
      <div class="fish-image">
        <img 
          :src="fish.fish_img_url || `/images/fish/${fish.species_name}.jpg`" 
          :alt="fish.species_name"
          @error="handleImageError"
        />
      </div>
      <div class="fish-info">
        <p class="species-name" v-if="fish.species_name">{{ fish.species_name }}</p>
        <div class="fish-actions">
          <el-button type="primary" size="small" @click="viewFishDetail(fish)">查看详情</el-button>
        </div>
      </div>
    </el-card>
  </el-col>
</el-row>
    
    <!-- 鱼类详情对话框 -->
    <el-dialog :title="selectedFish?.species_name" v-model="detailVisible" width="600px">
      <div v-if="selectedFish" class="fish-detail">
        <div class="detail-image">
          <!-- 详情页图片占位符 -->
          <div class="detail-image-content">
            <img 
              :src="selectedFish.fish_img_url || `/images/fish/${selectedFish.species_name}.jpg`" 
              :alt="selectedFish.species_name" 
              class="detail-fish-image"
              @error="handleDetailImageError"
            />
          </div>
        </div>
        <div class="detail-info">
          <p><strong>分布:</strong> {{ selectedFish.distribution || '暂无数据' }}</p>
          <p><strong>习性:</strong> {{ selectedFish.habitat_diet || '暂无数据' }}</p>
          <p><strong>经济价值:</strong> {{ selectedFish.economic_significance || '暂无数据' }}</p>
          <p style="color:deeppink;"><strong>推荐钓法:</strong> {{ selectedFish.recommended_fishing_methods || '暂无数据' }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 导入Vue相关功能
import { ref, computed, onMounted } from 'vue'
// 导入路由
import { useRouter } from 'vue-router'
// 导入Element Plus的消息提示组件
import { ElMessage,ElMessageBox } from 'element-plus'
// 导入Element Plus图标组件
import { Picture } from '@element-plus/icons-vue'
// 导入API
import { fishAPI } from '@/api'

export default {
  name: 'FishView',  // 组件名称
  components: {
    Picture  // 注册Picture图标组件
  },
  setup() {  // Vue 3 Composition API的setup函数
    const router = useRouter()  // 获取路由实例
    
    // 定义响应式变量
    const fishSearch = ref('')  // 搜索关键词
    const detailVisible = ref(false)  // 详情对话框可见性
    const selectedFish = ref(null)  // 当前选中的鱼类
    const fishes = ref([])  // 所有鱼类数据
    const loading = ref(false)  // 加载状态
    const error = ref('')  // 错误信息
    

    const handleImageError = (event) => {
      // 当图片加载失败时，显示默认占位图
      const img = event.target
      img.style.display = 'none'
      
      // 创建占位符
      const placeholder = document.createElement('div')
      placeholder.className = 'placeholder-image'
      placeholder.innerHTML = '<el-icon :size="48" color="#C0C4CC"><Picture /></el-icon><p>图片加载失败</p>'
      
      // 插入占位符
      img.parentNode.appendChild(placeholder)
    }
    
    const handleDetailImageError = (event) => {
      // 详情页图片加载失败时显示默认占位符
      const img = event.target
      img.style.display = 'none'
      
      // 创建占位符
      const placeholder = document.createElement('div')
      placeholder.className = 'placeholder-image detail-placeholder'
      placeholder.innerHTML = '<el-icon :size="48" color="#C0C4CC"><Picture /></el-icon><p>图片加载失败</p>'
      
      // 插入占位符
      img.parentNode.appendChild(placeholder)
    }
// 获取鱼类数据的异步函数
const fetchFishes = async () => {
  try {
    loading.value = true
    error.value = ''
    
    const response = await fishAPI.getFishList()
    
    if (response.code === 0 && Array.isArray(response.data)) {
      fishes.value = response.data.filter(fish => 
        fish !== null && 
        fish !== undefined && 
        fish.id !== undefined && 
        fish.id !== null &&
        fish.species_name !== undefined &&
        fish.species_name !== null
      )
    } else {
      fishes.value = []
    }
    
    if (fishes.value.length === 0) {
      ElMessage.warning('暂无有效的鱼类数据')
    }
  } catch (err) {
    console.error('获取鱼类数据失败:', err)
    error.value = '获取鱼类数据失败，服务器梦游中...'
    // 使用 MessageBox 弹框替代原来的 ElMessage
    ElMessageBox.alert(
      '无法连接到服务器或服务器出现错误，请稍后再试。',
      '数据加载失败',
      {
        confirmButtonText: '确定',
        type: 'error'
      }
    )
  } finally {
    loading.value = false
  }
}
    
    // 搜索函数（目前直接调用fetchFishes）
    const searchFishes = () => {
      fetchFishes()
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      fetchFishes()
    })
    
 // 计算属性：过滤后的鱼类列表
const filteredFishes = computed(() => {
  const validFishes = fishes.value.filter(fish => 
    fish &&
    fish.id !== undefined && 
    fish.id !== null &&
    fish.species_name
  )

  if (!fishSearch.value) {
    return validFishes
  }

  return validFishes.filter(fish =>
    fish.species_name.includes(fishSearch.value)
  )
})
    
    // 查看鱼类详情函数
    const viewFishDetail = (fish) => {
      // 跳转到鱼类详情页
      router.push(`/fish/${fish.id}`)
    }
    
    // 返回给模板使用的变量和函数
    return {
      fishSearch,
      filteredFishes,
      detailVisible,
      selectedFish,
      loading,
      error,
      viewFishDetail,
      searchFishes
    }
  }
}
</script>

<style scoped>

/* 鱼类模块容器样式增强 */
.fish-module {
  background-color: #fff;
  border-radius: 6px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border: 1px solid #ebeef5; /* 添加边框 */
}


/* 过滤控件容器样式 */
.filter-controls {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
}

/* 搜索输入框宽度 */
.search-input {
  width: 300px;
}

/* 加载状态样式 */
.loading {
  padding: 20px;
  text-align: center;
}

/* 无数据状态样式 */
.no-data {
  padding: 40px 0;
}

/* 错误状态样式 */
.error {
  padding: 20px 0;
}

/* 鱼类列表样式 */
.fish-list {
  margin-top: 20px;
}

/* 鱼类卡片样式 */
.fish-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
  border: 1px solid #dcdfe6; /* 添加明显边框 */
  border-radius: 6px; /* 稍微圆角 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 鱼类卡片悬停效果 */
.fish-card:hover {
  transform: translateY(-5px);
  border-color: #409eff; /* 悬停时改变边框颜色 */
  box-shadow: 0 4px 16px 0 rgba(64, 158, 255, 0.2);
}


/* 鱼类图片容器样式 */
.fish-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 6px 6px 0 0;
  background-color: #f5f7fa;
}

.fish-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.fish-image img:hover {
  transform: scale(1.05);
}

/* 鱼类图片容器样式增强 */
.fish-image-content {
  max-width: 100%;
  max-height: 100%;
  object-fit: cover;
}

.placeholder-image {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
}

/* 占位图片容器样式 */
.placeholder-image {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
}

/* 详情页占位图片样式 */
.detail-placeholder {
  height: 200px;
  background-color: #f5f7fa;
}

/* 鱼类信息容器样式 */
.fish-info {
  padding: 15px;
}

/* 鱼类名称样式 */
.fish-info h3 {
  margin: 0 0 10px 0;
  color: #303133;
  height: 60px; /* 固定高度，大约显示2-3行 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制显示2行 */
  -webkit-box-orient: vertical;
  line-height: 1.5;
}

/* 学名样式 */
.species-name {
  font-style: italic;
  color: #909399;
  margin: 0 0 8px 0;
  font-size: 14px;
  height: 40px; /* 固定高度 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 限制显示2行 */
  -webkit-box-orient: vertical;
  line-height: 1.4;
}

/* 鱼类操作按钮容器样式 */
.fish-actions {
  display: flex;
  justify-content: space-between;
}

/* 鱼类详情容器样式 */
.fish-detail {
  display: flex;
  gap: 20px;
}

/* 详情图片容器样式 */
.detail-image {
  flex: 1;
}
.detail-image-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
}

.detail-fish-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

/* 详情信息容器样式 */
.detail-info {
  flex: 2;
}
/* 详情信息段落样式增强 */
.detail-info p {
  margin-bottom: 10px;
  line-height: 1.6;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #f5f7fa; /* 轻微背景色 */
  border: 1px solid #ebeef5; /* 边框 */
}
/* 搜索输入框样式增强 */
.search-input :deep(.el-input__wrapper) {
  border: 2px solid #409eff !important;
  border-radius: 4px;
  box-shadow: 0 0 0 1px #409eff inset !important;
}
.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff !important;
  box-shadow: 0 0 0 1px #409eff inset !important;
}
/* 鱼类卡片样式增强 */
.fish-card {
  margin-bottom: 20px;
  transition: transform 0.3s;
  border: 1px solid #dcdfe6; /* 添加明显边框 */
  border-radius: 6px; /* 稍微圆角 */
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
/* 对话框样式增强 */
:global(.el-dialog) {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  box-shadow: 0 4px 24px 0 rgba(0, 0, 0, 0.15) !important;
}
:global(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
}
:global(.el-dialog__body) {
  padding: 20px;
}

:global(.el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px;
}

/* 图片占位符样式 */
.placeholder-image {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  color: #909399;
  font-size: 14px;
  min-height: 200px;
}

.placeholder-image p {
  margin-top: 10px;
  margin-bottom: 0;
}

.detail-placeholder {
  min-height: 300px;
}

/* 详情对话框图片样式 */
.detail-image {
  width: 100%;
  margin-bottom: 20px;
}

.detail-image-content {
  width: 100%;
  height: 300px;
  overflow: hidden;
  border-radius: 8px;
  background-color: #f5f7fa;
}

.detail-fish-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.detail-fish-image:hover {
  transform: scale(1.02);
}

/* 过滤控件容器样式微调 */
.filter-controls {
  display: flex;
  margin-bottom: 20px;
  gap: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 6px;
  background-color: #f5f7fa;
}
</style>